package com.example.group_20.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.group_20.entity.*;
import com.example.group_20.mapper.*;
import com.example.group_20.service.TeacherService;
import com.example.group_20.utils.JwtUtils;
import com.example.group_20.utils.Result;
import com.example.group_20.utils.SLogUtils;
import com.example.group_20.utils.TLogUtils;
import org.apache.catalina.core.ApplicationContext;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: 栋
 * @data: 2023/8/11
 * @descriptions:
 */
@Service
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private StudentsMapper studentsMapper;
    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private RateMapper rateMapper;
    @Autowired
    private FilesMapper filesMapper;
    @Autowired
    private TLogMapper tLogMapper;

    @Override
    public Result login(String t_id, String pwd) {
        Teachers teachers = teacherMapper.findByid(t_id);
        if(teachers!=null){
            if(pwd.equals(teachers.getT_password())) {
                String token = JwtUtils.generateToken(t_id);
                return Result.Ok().data("token", token);
            }
        }
        return Result.Error().msg("Account and password are incorrect.");
    }

    @Override
    public Result getInfor(String token) {
        String t_id = JwtUtils.getClaimsByToken(token).getSubject();
        Teachers byid = teacherMapper.findByid(t_id);
        return Result.Ok().data("teachers",byid);
    }

    @Override
    public Result logOut() {
        return Result.Ok().data("sucess","sucess");
    }

    @Override
    public Result showInfor(String token) {
        String t_id = JwtUtils.getClaimsByToken(token).getSubject();
        Teachers teachers = teacherMapper.findByid(t_id);
        List<Group> groups = groupMapper.findByGroupAndStudents(t_id);
        for (Group group : groups) {
            Students student=null;
            List<Students> students = group.getStudents();
            for(int i=0;i<students.size();i++){
                if(students.get(i).getLeader()==1){
                    student = students.get(i);
                    students.remove(i);
                    students.add(0,student);
                    break;
                }

            }
        }
        return Result.Ok()
                .data("list",groups)
                .data("teachers",teachers);
    }

    @Override
    public Result updateInfor(Teachers teachers) {
        Teachers t = teacherMapper.findByid(teachers.getT_id());
        t.setT_email(teachers.getT_email());
        t.setT_tel(teachers.getT_tel());
        int res=teacherMapper.updateInfor(t);
        if(res!=0){
            return Result.Ok().msg("修改成功").data("message","success");
        }else {
            return Result.Error().msg("修改失败").data("message","error");
        }
    }

    @Override
    public Result updatePwd(Teachers teachers, String newPwd) {
        String t_id=teachers.getT_id();
        Teachers t = teacherMapper.findByid(t_id);
        if(teachers.getT_password().equals(t.getT_password())) {
            t.setT_password(newPwd);
            int res = teacherMapper.updateInfor(t);
            if (res != 0) {
                return Result.Ok().msg("修改成功").data("message", "success");
            } else {
                return Result.Error().msg("修改失败").data("message", "error");
            }
        }else{
            return Result.Error().msg("密码错误").data("message", "error");
        }
    }

    @Override
    public Result showFile(String token) {
        String t_id = JwtUtils.getClaimsByToken(token).getSubject();
        List<Group> groups = groupMapper.findByTid(t_id);
        List<FilesInfor> list=new ArrayList<>();
        for (Group group : groups) {
            boolean b = list.addAll(filesMapper.findByGroup(group.getGroup_id()));
        }
        List<Rate> rate = rateMapper.findAll();
        List<Category> category = categoryMapper.findAll();
        return Result.Ok()
                .data("files",list)
                .data("rate",rate)
                .data("category",category)
                .data("groups",groups);
    }

    @Override
    public Result beforCorrectFile(String f_id) {
        FilesInfor file = filesMapper.findById(f_id);
        List<Rate> rate = rateMapper.findAll();
        List<Category> category = categoryMapper.findAll();

        return Result.Ok()
                .data("file",file)
                .data("rate",rate)
                .data("category",category);
    }

    @Override
    public Result correctFile(Map<String, Object> mp) {
        StringBuilder f_id=new StringBuilder("");
        int rate=0;
        StringBuilder comment=new StringBuilder("");
        StringBuilder t_id=new StringBuilder("");
        if(mp.containsKey("f_id")){
            f_id.append(mp.get("f_id"));
        }
        if(mp.containsKey("rate")){
            rate=(Integer) mp.get("rate");
        }
        if(mp.containsKey("comment")){
            comment.append(mp.get("comment"));
        }
        if(mp.containsKey("t_id")){
            t_id.append(mp.get("t_id"));
        }
        Teachers t = teacherMapper.findByid(t_id.toString());
        FilesInfor file = filesMapper.findById(f_id.toString());

        Date date=Date.valueOf(LocalDate.now());
        Time time=Time.valueOf(LocalTime.now());
        file.setTeacher_id(t_id.toString());
        file.setTeacher_name(t.getT_name());
        file.setComments(comment.toString());
        file.setCheck_date(date);
        file.setCheck_time(time);
        file.setStatus(rate);
        filesMapper.updateFile(file);
        List<TLogInfor> tLogInfors = tLogMapper.finAll();
        StringBuilder lastId=new StringBuilder("");
        if(!tLogInfors.isEmpty()){
            int size1 = tLogInfors.size();

            TLogInfor tLogInfor=tLogInfors.get(size1-1);
            lastId.append(tLogInfor.getId());
        }
        String tLogId= TLogUtils.getId(lastId.toString());
        TLogInfor tLogInfor=new TLogInfor(tLogId,file.getFile_id(),file.getName(),file.getGroup_id(),t.getT_id(),date,time,comment.toString(),rate);
        tLogMapper.insert(tLogInfor);

        return Result.Ok().msg("提交成功").data("message","success");
    }

    @Override
    public Result showLogInfor(String token) {
        String t_id = JwtUtils.getClaimsByToken(token).getSubject();
        List<TLogInfor> TLogInfor = tLogMapper.findByTid(t_id);
        List<Rate> rate = rateMapper.findAll();
        return Result.Ok()
                .data("TLogInfor",TLogInfor)
                .data("rate",rate);
    }

    @Override
    public Result sendMsg(Map<String, Object> mp) {
        StringBuilder s_id=new StringBuilder("");
        StringBuilder teacher_id=new StringBuilder("");
        StringBuilder msg=new StringBuilder("");
        if(mp.containsKey("s_id")){
            s_id.append(mp.get("s_id"));
        }
        if(mp.containsKey("teacher_id")){
            teacher_id.append(mp.get("teacher_id"));
        }
        if(mp.containsKey("msg")){
            msg.append(mp.get("msg"));
        }
        Date date=Date.valueOf(LocalDate.now());
        Time time=Time.valueOf(LocalTime.now());
        Students students = studentsMapper.findByid(s_id.toString());
        Teachers teachers = teacherMapper.findByid(teacher_id.toString());
        if(students==null){
            return Result.Error().msg("发送对象不存在，请检查老师工号").data("message","error");
        }
        Chat chat=new Chat(0,msg.toString(),teacher_id.toString(),teachers.getT_name(),s_id.toString(),students.getS_name(),null,date,time,null,null,0);
        chatMapper.insert(chat);
        return Result.Ok().data("message","success").msg("发送成功");
    }

    @Override
    public Result showSendMsg(String token) {
        String t_id = JwtUtils.getClaimsByToken(token).getSubject();
        List<Chat> bySentId = chatMapper.findBySentId(t_id);
        return Result.Ok().data("msg",bySentId);
    }

    @Override
    public Result showReciveMsg(String token) {
        String t_id = JwtUtils.getClaimsByToken(token).getSubject();
        List<Chat> byReciveId = chatMapper.findByReciveId(t_id);
        return Result.Ok().data("msg",byReciveId);
    }

    @Override
    public Result reply(Map<String, Object> mp) {
        int id=0;
        StringBuilder response=new StringBuilder("");
        if(mp.containsKey("id")){
            id=(Integer) mp.get("id");
        }
        if(mp.containsKey("content")){
            response.append(mp.get("content"));
        }
        Date date=Date.valueOf(LocalDate.now());
        Time time=Time.valueOf(LocalTime.now());
        Chat chat = chatMapper.findByid(id);
        chat.setResp_date(date);
        chat.setResp_time(time);
        chat.setResponse(response.toString());
        chat.setStatus(1);
        int res = chatMapper.updateChatInfor(chat);
        if(res==1){
            return Result.Ok().msg("回复成功").data("message","success");
        }else{
            return Result.Error().msg("回复失败").data("message","error");
        }
    }

    @Override
    public Result downloadFile(String file_id, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        FilesInfor filesInfor = filesMapper.findById(file_id);
        ServletContext servletContext= req.getServletContext();


        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filesInfor.getName(),"UTF-8"));
        InputStream resourceAsStream = servletContext.getResourceAsStream(filesInfor.getPath());
        OutputStream outputStream = resp.getOutputStream();
        IOUtils.copy(resourceAsStream,outputStream);
        return Result.Ok();
    }

    @Override
    public Result selectLeader(Map<String, Object> mp) {
        StringBuilder group_id=new StringBuilder("");
        StringBuilder s_id=new StringBuilder("");
        if(mp.containsKey("group_id")){
            group_id.append(mp.get("group_id"));
        }
        if(mp.containsKey("s_id")){
            s_id.append(mp.get("s_id"));
        }
        Group group = groupMapper.findByid(Integer.valueOf(group_id.toString()));
        group.setS_id(s_id.toString());
        Students students = studentsMapper.findByid(s_id.toString());
        students.setLeader(1);
        UpdateWrapper<Group> groupUpdateWrapper=new UpdateWrapper<>();
        groupUpdateWrapper.eq("group_id",group.getGroup_id());
        groupMapper.update(group,groupUpdateWrapper);
        studentsMapper.updateInfor(students);
        List<Students> studentsList = studentsMapper.findByGroup(Integer.valueOf(group_id.toString()));
        Students student=new Students();
        for(int i=0;i<studentsList.size();i++){
            if(studentsList.get(i).getLeader()==1){
                student = studentsList.get(i);
                studentsList.remove(i);
                studentsList.add(0,student);
                break;
            }

        }
        return Result.Ok()
                .data("message","success")
                .data("students",studentsList)
                .msg("设置成功");
    }
}
